package com.quanyue.music.order.controller;

import com.github.binarywang.wxpay.bean.WxPayOrderNotifyResponse;
import com.github.binarywang.wxpay.bean.result.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.quanyue.music.order.service.PayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "支付")
@RestController
public class PayController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PayService payService;

    @ApiOperation(value = "微信支付回调")
    @PostMapping(value = "/wechat/pay/confirm")
    public String payNotify(@RequestBody String content) {
        try {
            WxPayOrderNotifyResult result = WxPayOrderNotifyResult.fromXML(content);
            logger.info("微信支付回调结果对象WECHAT_RESULT：{}", result);
            payService.handlePayConfirm(result);
            return WxPayOrderNotifyResponse.success("处理成功!");
        } catch (WxErrorException e) {
            logger.error("支付失败，" + e.getMessage(), e);
            return WxPayOrderNotifyResponse.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "微信支付回调")
    @PostMapping(value = "/wechat/refund/confirm")
    public String refundNotify(@RequestBody String content) {
        try {
            WxPayRefundResult result = WxPayRefundResult.fromXML(content, WxPayRefundResult.class);
            logger.info("微信退款回调结果对象：{}", result);
            payService.handleRefundConfirm(result);
            return WxPayOrderNotifyResponse.success("处理成功!");
        } catch (Exception e) {
            logger.error("退款验证失败，" + e.getMessage(), e);
            return WxPayOrderNotifyResponse.fail(e.getMessage());
        }
    }
}
